package com.gzhryc.socket.message;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.xml.XmlTools;
import com.gzhryc.socket.SocketMessage;

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class TextWebSocketMessage implements SocketMessage{
	
	static Logger log = Logger.getLogger(TextWebSocketMessage.class);
	
	String content;
	TextWebSocketFrame textWebSocketFrame;
	
	public TextWebSocketMessage() {}
	
	public TextWebSocketMessage(String content) {
		this.content = content;
		this.textWebSocketFrame = new TextWebSocketFrame(content);
	}
	
	public TextWebSocketMessage(byte[] bytes) {
		try {
    		this.content = new String(bytes, "UTF-8");
    		this.textWebSocketFrame = new TextWebSocketFrame(this.content);
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
		}
    }
	
	public TextWebSocketFrame getTextWebSocketFrame() {
		return textWebSocketFrame;
	}
	
	public void setBytes(byte[] bytes) {
    	try {
    		this.content = new String(bytes, "UTF-8");
    		this.textWebSocketFrame = new TextWebSocketFrame(this.content);
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
		}
    }

	@Override
	public byte[] getBytes() {
		if(this.content != null) {
			return this.content.getBytes(Charset.forName("UTF-8"));
		}
		return null;
	}

	@Override
	public String getString() {
		return this.content;
	}

	@Override
	public <T> T fromJSON(Class<T> tClass) {
		if(StringUtils.isNotBlank(this.content)) {
            return JsonTools.fromJson(this.content, tClass);
        }
        return null;
	}

	@Override
	public <T> T fromXML(Class<T> tClass) {
		if(StringUtils.isNotBlank(this.content)) {
            return XmlTools.changToObject(this.content, tClass, false);
        }
		return null;
	}

	@Override
	public Object getAttribute(String key) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setAttribute(String key, Object obj) {
		// TODO Auto-generated method stub
		
	}
}
